package com.chilly.other.collection;

/**
 * LRU最近最久未使用置换算法，通过LinkedHashMap实现
 * <p>
 * Created by Chilly Cui on 2020/11/26.
 */

import java.util.LinkedHashMap;
import java.util.Map;

public class LRUCache<K, V> extends LinkedHashMap<K, V> {
    // Sample use: this override will allow the map to grow up to MAX_ENTRIES
    // entries and then delete the eldest entry each time a new entry is
    // added, maintaining a steady state of MAX_ENTRIES entries.
    private int MAX_ENTRIES;

    public LRUCache(int MAX_ENTRIES) {
        super(16, 0.75f, true);
        this.MAX_ENTRIES = MAX_ENTRIES;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return size() > MAX_ENTRIES;
    }

    public static void main(String[] args) {
        LRUCache<String, Object> lruCache = new LRUCache<>(3);
        lruCache.put("a", "abstract");
        lruCache.put("b", "basic");
        lruCache.put("c", "call");
        lruCache.get("a");
        lruCache.put("d", "滴滴滴");
        System.out.println(lruCache); // 输出为：{c=call, a=abstract, d=滴滴滴}    }
    }
}
